//
//  RssFlyApp.swift
//  RssFly
//
//  Created by shen on 2023/10/13.
//

import CoreData
import SwiftUI

import SDWebImage
import SDWebImageWebPCoder
import SDWebImageSVGCoder

#if canImport(Sparkle)
import Sparkle
#endif

@main
struct RssFlyApp: App {
    // 适配UIAppDelegate
    #if !os(macOS)
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    #endif

    @Environment(\.openURL) private var openURL

    @AppStorage("LastCleanup") private var lastCleanup: Double?
    @AppStorage("UserColorScheme") private var userColorScheme: UserColorScheme = .system
    @AppStorage("UseSystemBrowser") private var useSystemBrowser = false

    @StateObject private var networkMonitor = NetworkMonitor()

    let persistenceController = PersistenceController.shared

    #if canImport(Sparkle)
    private let updaterController: SPUStandardUpdaterController
    #endif

    var body: some Scene {
        WindowGroup {
            RootView()
                .environment(\.managedObjectContext, persistenceController.container.viewContext)
                .environment(\.useSystemBrowser, useSystemBrowser)
                .environmentObject(networkMonitor)
                .preferredColorScheme(userColorScheme.colorScheme)
                .task { performCleanup() }
        }
        .handlesExternalEvents(matching: ["*"]) // 恢复应用/打开新窗口
        .commands {
            #if canImport(Sparkle)
            CommandGroup(after: .appInfo) {
                // TODO: - 检查更新
                logger.debug("检查更新")
//                CheckForUpdatesView(updater: updaterController.updater)
            }
            #endif
            CommandGroup(replacing: .help) {
                Button {
                    openURL(URL(string: "https://den.io/help/")!)
                } label: {
                    Text("\(Bundle.main.name) Help", comment: "Button label.")
                }
                // TODO: - Acknowledgements & LicencePlist
//                #if os(macOS)
//                Divider()
//                Button {
//                    if let url = Bundle.main.url(
//                        forResource: "Acknowledgements",
//                        withExtension: "html"
//                    ) {
//                        NSWorkspace.shared.open(url)
//                    }
//                } label: {
//                    Text("Acknowledgements", comment: "Button label.")
//                }
//                #endif
            }
        }
        #if os(macOS)
        .defaultSize(width: 1200, height: 800)
        #endif

        #if os(macOS)
        Settings {
            // TODO: - 设置表单
            SettingsForm()
        }
        #endif
    }

    init() {
        // mac检查更新
        #if canImport(Sparkle)
        updaterController = SPUStandardUpdaterController(
            startingUpdater: true,
            updaterDelegate: nil,
            userDriverDelegate: nil
        )
        #endif
        setupImageHandling()
    }

    private func performCleanup() {
        if let lastCleanup = lastCleanup {
            let nextCleanup = Date(timeIntervalSince1970: lastCleanup) + 7 * 24 * 60 * 60
            if nextCleanup > .now {
                logger.debug("Next cleanup after \(nextCleanup.formatted(), privacy: .public)")
            }
            return
        }

        persistenceController.container.performBackgroundTask { context in
            guard let profiles = try? context.fetch(Profile.fetchRequest()) as [Profile] else { return }
            for profile in profiles {
                try? CleanupUtility.removeExpiredHistory(context: context, profile: profile)
                CleanupUtility.trimSearches(context: context, profile: profile)
            }
            try? CleanupUtility.purgeOrphans(context: context)
            try? context.save()
        }

        lastCleanup = Date.now.timeIntervalSince1970
    }

    private func setupImageHandling() {
        // Add additional image format support
        SDImageCodersManager.shared.addCoder(SDImageSVGCoder.shared)
        SDImageCodersManager.shared.addCoder(SDImageWebPCoder.shared)

        // Explicit list of accepted image types so servers may decide what to respond with
        let imageAcceptHeader: String = ImageMIMEType.allCases.map { mimeType in
            mimeType.rawValue
        }.joined(separator: ",")
        SDWebImageDownloader.shared.setValue(imageAcceptHeader, forHTTPHeaderField: "Accept")
    }
}

#if !os(macOS)
class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
        print("launch")
        return true
    }

    func application(_: UIApplication, supportedInterfaceOrientationsFor _: UIWindow?) -> UIInterfaceOrientationMask {
        return Device.deviceType == .ipad
            ? UIInterfaceOrientationMask.all
            : UIInterfaceOrientationMask.portrait
    }
}
#endif
